<script setup lang="ts">
import {
  ArrowDown,
  ChatDotRound,
  DataLine,
  Document,
  Files,
  Message,
  Notification,
  Plus,
  VideoCamera
} from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import {
  userEditPasswordService, userGetIllegalListService,
  userGetUserInfoService,
  userUpdateUserInfoService
} from '@/api/user'
import router from '@/router'
import { useCountStore } from '@/stores/StuStatisticsCount'

const editUserInfo = ref(false)

const personForm = ref({
  stuId: '',
  username: '',
  identify: '',
  school: '',
  avatar: ''
})

enum IdentifyType {
  'student' = '学生',
  'teacher' = '教师'
}

const getUserInfo = async () => {
  const res = await userGetUserInfoService()
  personForm.value = res.data.data
  useUserStore().setAvatar(res.data.data.avatar)
}

getUserInfo()

// 上传成功后处理
const handleAvatarSuccess = (response: any) => {
  if (response.code === 1) {
    personForm.value.avatar = response.data // 假设后端返回图片路径在 data 字段
    console.log(response.data)
    ElMessage.success('图片上传成功！')
  } else {
    ElMessage.error('图片上传失败，请重试！')
  }
}

// 上传前校验
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 5
  if (!isImage) {
    ElMessage.error('只能上传图片格式文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 5MB！')
    return false
  }
  return true
}

// 请求头
const userStore = useUserStore()
const uploadHeaders = ref({
  token: `${userStore.token}` // 假设 userStore.token 存储的是有效的 Token
})

const submit = async () => {
  await ElMessageBox.confirm('确认提交吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await userUpdateUserInfoService(personForm.value)
  ElMessage.success('修改成功！')
  await getUserInfo()
}

const exit = async () => {
  await ElMessageBox.confirm('确认退出吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  ElMessage.success('退出成功！')
  await router.push('/login')
  useUserStore().token = ''
}

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordDialogForm = ref()

const passwordRule = {
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/
        if (!passwordRegex.test(value)) {
          callback(new Error('新密码长度需为8到20位，且包含字母和数字'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ],
  confirmPassword: [{ required: true, message: '请再次输入新密码', trigger: 'blur' }]
}

const editPassword = ref(false)

// 修改密码
const passwordSubmit = async () => {
  const valid = passwordDialogForm.value.validate()
  if (valid) {
    if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
      ElMessage.error('两次输入的新密码不一致')
      return
    }
    await userEditPasswordService(passwordForm.value)
    ElMessage.success('修改成功！')
    passwordForm.value.oldPassword = ''
    passwordForm.value.newPassword = ''
    passwordForm.value.confirmPassword = ''
    editPassword.value = false
  }
}

const countStore = useCountStore()

onMounted(() => {
  countStore.getContentCount()
  console.log('userId:' + userStore.getUserId)
})

const isShowMessage = ref(false)
const showMessage = ()=>{
  isShowMessage.value = true
  getIllegalList()
}
const messageContent = ref([
  {
    title: '通知公告',
    content: '欢迎来到多媒体网站制作课程！',
    topicPublishTime:'2024-12-29',
    createTime: '2024-12-29',
    reason:'违规内容'
  },
])


const getIllegalList = async () => {
  const res = await userGetIllegalListService()
  console.log(res.data.data)
  messageContent.value = res.data.data
}


</script>

<template>
  <div id="main">
    <div class="edu-container">
      <div class="edu-part">
        <div style="display: flex; align-items: center">
          <h1>多媒体网站制作</h1>
          <el-tag style="margin-left: 10px">私有</el-tag>
        </div>
        <h3>教师:杨兵</h3>

        <div class="user-container">
          <img
            :src="personForm.avatar"
            width="50"
            height="50"
            style="clip-path: circle(50% at 50% 50%)"
            alt=""
          />
          <el-dropdown :hide-on-click="false">
            <span class="el-dropdown-link">
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="editUserInfo = true">用户详情</el-dropdown-item>
                <el-dropdown-item @click="editPassword = true">修改密码</el-dropdown-item>
                <el-dropdown-item @click="exit">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button
            @click="showMessage"
            type="text"
            style="font-size: 30px; margin-left: 10px"
            :icon="Message"
          ></el-button>
        </div>
      </div>
    </div>
    <div class="main-container">
      <el-row>
        <el-col style="background-color: white" :span="4">
          <el-menu class="el-menu-vertical" default-active="/student/notification" router>
            <el-menu-item index="/student/notification">
              <el-icon>
                <Notification />
              </el-icon>
              通知公告
              <el-tag type="primary" style="margin-left: 10px" round
                >{{ countStore.contentCount.notificationCount }}
              </el-tag>
            </el-menu-item>
            <el-sub-menu index="2">
              <template #title>
                <el-icon>
                  <Files />
                </el-icon>
                学习资料
              </template>
              <el-menu-item index="/student/resource/video">
                <el-icon>
                  <VideoCamera />
                </el-icon>
                视频资料
                <el-tag type="primary" style="margin-left: 10px" round
                  >{{ countStore.contentCount.videoCount }}
                </el-tag>
              </el-menu-item>
              <el-menu-item index="/student/resource/document">
                <el-icon>
                  <Document />
                </el-icon>
                文档资料
                <el-tag type="primary" style="margin-left: 10px" round
                  >{{ countStore.contentCount.documentCount }}
                </el-tag>
              </el-menu-item>
              <el-menu-item index="/student/resource/courseware">
                <el-icon>
                  <DataLine />
                </el-icon>
                课件资料
                <el-tag type="primary" style="margin-left: 10px" round
                  >{{ countStore.contentCount.courseWareCount }}
                </el-tag>
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item index="/student/test">
              <el-icon>
                <Document />
              </el-icon>
              考试发布
              <el-tag type="primary" style="margin-left: 10px" round
                >{{ countStore.contentCount.testPublishCount }}
              </el-tag>
            </el-menu-item>
            <el-menu-item index="/student/topic">
              <el-icon>
                <ChatDotRound />
              </el-icon>
              话题讨论
            </el-menu-item>
          </el-menu>
        </el-col>
        <el-col :span="20">
          <Transition name="slide-fade">
            <router-view></router-view>
          </Transition>
        </el-col>
      </el-row>
    </div>
  </div>

  <el-dialog v-model="editUserInfo" id="userInfo" title="用户信息" width="500">
    <el-form>
      <el-form-item label="用户头像">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8000/student/common/upload"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          name="file"
        >
          <img v-if="personForm.avatar" :src="personForm.avatar" class="avatar" alt="上传的图片" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input
          placeholder="用户名"
          v-model="personForm.username"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="学号">
        <el-input placeholder="学号" v-model="personForm.stuId" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="学校">
        <el-input placeholder="学校" v-model="personForm.school" style="width: 300px"></el-input>
      </el-form-item>
      <el-form-item label="身份">
        <el-select
          disabled
          v-model="IdentifyType[personForm.identify]"
          placeholder="身份"
          style="width: 300px"
        >
          <el-option>学生</el-option>
          <el-option>教师</el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="submit">修改</el-button>
  </el-dialog>

  <el-dialog v-model="editPassword" title="修改密码" width="500">
    <el-form ref="passwordDialogForm" :model="passwordForm" :rules="passwordRule">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input
          placeholder="旧密码"
          type="password"
          show-password
          v-model="passwordForm.oldPassword"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          placeholder="新密码长度需为8到20位，且包含字母和数字"
          type="password"
          show-password
          v-model="passwordForm.newPassword"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          placeholder="确认密码"
          type="password"
          show-password
          v-model="passwordForm.confirmPassword"
          style="width: 300px"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="passwordSubmit">修改</el-button>
  </el-dialog>

  <el-dialog style="background: whitesmoke" v-model="isShowMessage" width="500">
    <h1>信息</h1>
    <el-scrollbar height="500px" style="margin-top: 10px">
      <div v-for="message in messageContent" class="message">
        <h3 style="color: red">违规信息</h3>
        <el-divider style="margin: 12px 0" border-style="dashed" />
        <p>您在{{ message.topicPublishTime }}发布的内容</p>
        <el-text style="width: 100%;" truncated>"{{message.title}}"</el-text>
        <p>违反了教育平台使用规则，我们已删除您的内容，请遵守教育平台使用规则。</p>
        <p style="font-weight: bold">违规原因：{{ message.reason }}</p>
        <p>发布时间：{{ message.createTime }}</p>
      </div>
    </el-scrollbar>
  </el-dialog>
</template>

<style scoped>
#main {
  height: 100vh;
}

.edu-container {
  position: relative;
  width: 100vw;
  height: 15vh;
  border: 1px solid black;
  padding: 10px;
  color: white;
  background-image: url('https://www-cdn.educoder.net/static/classroom-banner.9f9f21d0.png');
  background-size: cover;
}

.edu-part {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  position: relative;
  width: 70vw;
  left: 50%;
  height: 100%;
  transform: translateX(-50%);
}

.user-container {
  display: flex;
  position: absolute;
  right: 20px;
  top: 20px;
  align-items: center;

  #avatar {
    overflow: hidden;
    height: 50px;
    width: 50px;
    clip-path: circle(50% at 50% 50%);
  }

  .el-icon--right {
    color: white;
  }
}

.main-container {
  position: relative;
  width: 70vw;
  left: 50%;
  transform: translateX(-50%);
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
  margin-top: 20px;
  overflow: hidden;
  border-radius: 10px;
}

/*
  进入和离开动画可以使用不同
  持续时间和速度曲线。
*/
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s ease-out;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(40px);
  opacity: 0;
}

.avatar-uploader {
  width: 50px; /* 固定宽度 */
  height: 50px; /* 高度根据宽度自动调整 */
  overflow: hidden;
  border-radius: 5px;
  clip-path: circle(50% at 50% 50%);
}

.avatar-uploader .avatar {
  width: auto;
  height: 50px;
  display: block;
  transition: all 0.3s;
}

.el-menu-item.is-active {
  background-color: #d7eefb !important;
  color: #409eff !important;
  border-radius: 10px;
  animation: btn-animation 0.3s ease-in-out forwards;
}

.el-menu-item:hover {
  color: #409eff !important;
  background-color: transparent;
}

.message {
  display: flex;
  flex-direction: column;
  width: 90%;
  height: auto;
  background-color: white;
  border-radius: 10px;
  margin-bottom: 10px;
  padding: 10px;
  line-height: 2rem;
}

@keyframes btn-animation {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}
</style>
